package cn.lyz.craft.web.controller;

import java.util.List;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.lyz.craft.common.R;
import cn.lyz.craft.service.entity.Menu;
import cn.lyz.craft.service.service.MenuService;
import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("/api/menus")
@RequiredArgsConstructor
public class MenuController {
    private final MenuService menuService;

    @GetMapping
    public R<List<Menu>> getAllMenus() {
        return R.success(menuService.findAll());
    }

    @GetMapping("/top")
    public R<List<Menu>> getTopLevelMenus() {
        return R.success(menuService.findByParentIsNull());
    }

    @GetMapping("/{id}")
    public R<Menu> getMenuById(@PathVariable Long id) {
        return R.success(menuService.findById(id));
    }

    @PostMapping
    public R<Menu> createMenu(@RequestBody Menu menu) {
        return R.success(menuService.save(menu));
    }

    @PutMapping("/{id}")
    public R<Menu> updateMenu(@PathVariable Long id, @RequestBody Menu menu) {
        menu.setId(id);
        return R.success(menuService.save(menu));
    }

    @DeleteMapping("/{id}")
    public R<Void> deleteMenu(@PathVariable Long id) {
        menuService.deleteById(id);
        return R.success();
    }
}